package com.example.jasonrpc.transport;

import com.example.jasonrpc.proto.Peer;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpTransportClient implements TransportClient{
    private String url;
    private static final String URL_FORMAT = "http://%s:%d";

    @Override
    public void connect(Peer peer) {
        this.url = String.format(HttpTransportClient.URL_FORMAT, peer.getHost(), peer.getPort());
    }

    /**
     * 将输入数据包装成http请求格式的数据
     * @param data
     * @return
     */
    @Override
    public InputStream write(InputStream data) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");

            conn.connect();
            IOUtils.copy(data, conn.getOutputStream());

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return conn.getInputStream();
            }else {
                return conn.getErrorStream();
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public void close() {

    }
}
